package com.github.butid.data.netty.springboot;

import com.github.butid.data.netty.annotation.CommandController;
import com.github.butid.data.netty.core.Command;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created By WangMing On 2019-12-07
 **/
@Slf4j
public class SpringContext implements ApplicationContextAware {

    //TODO 添加Command扫描机制

    private static ApplicationContext context;

    /**
     * 查找所有符合条件的Command对象
     * @param cmdType
     * @param cmdCode
     * @return
     */
    public static List<Command> findBeans(String cmdType, String cmdCode) {

        Map<String, Object> controllers = SpringContext.getBeansWithAnnotation(CommandController.class);
        List<Command> cmds = new ArrayList<>();

        controllers.forEach((k, v) -> {
            if(!(v instanceof Command)) return;

            CommandController anno = v.getClass().getAnnotation(CommandController.class);
            String annoCmdType = anno.cmdType();
            String annoCmdCode = anno.cmdCode();

            if(null == cmdType) return;
            if(! annoCmdType.equals(cmdType)) return;

            if(annoCmdCode.equals("*")){
                // contiune
            }else if(annoCmdCode.equals(cmdCode)){
                // contiune
            }else{
                return;
            }

            cmds.add((Command) v);
        });

        return cmds;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static <T> T getBean(Class<T> requiredType) throws BeansException {
        return context.getBean(requiredType);
    }

    public static <T> Map<String, T> getBeansOfType(Class<T> requiredType) throws BeansException {
        return context.getBeansOfType(requiredType);
    }

    public static Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> requiredType) throws BeansException {
        return context.getBeansWithAnnotation(requiredType);
    }

    public static Object getBean(String name) {
        return context.getBean(name);
    }

    public static <T> T getBean(String name, Class<T> requiredType) {
        return context.getBean(name, requiredType);
    }
}
